package com.example.demo.thread.ch5;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * 通用任务执行器
 *
 * @author: htc
 * @date: Created in 16:46 2019/1/14.
 */
public class TaskRunner {
    protected final BlockingQueue<Runnable> channel;
    protected volatile Thread workerThread;

    public TaskRunner(BlockingQueue<Runnable> channel) {
        this.channel = channel;
    }

    public TaskRunner() {
        this(new LinkedBlockingDeque<Runnable>());
    }

    public void init() {
        final Thread t = workerThread;
        if (null != t) {
            t.start();
        }
    }

    public void submit(Runnable task) throws InterruptedException {
        channel.put(task);
    }

    class WorkerThread extends Thread {
        @Override
        public void run() {
            Runnable task = null;
            try {
                //注意：下面这种写法实际上可能导致工作者线程永远无法终止(5.6节会解决这个问题)
                for (; ; ) {
                    task = channel.take();
                    task.run();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
            }
        }
    }
}

